<!--
 * @Description: 角色表单弹窗
-->
<template>
  <a-drawer :title="formTitle" :open="visible" @close="onClose">
    <template #closeIcon>
      <div class="express-bar"></div>
      <div class="express-btn">
        <CloseCircleOutlined :size="32" @click="onClose" />
      </div>
    </template>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ sm: 4, lg: 6 }">
      <a-card title="基本信息" class="smart-margin-bottom10">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :span="21">
            <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
              <a-col :xs="24" :lg="12" :xl="8" :xxl="8">
                <a-form-item label="名称" name="title">
                  <a-input v-model:value="form.title" placeholder="请输入名称" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="8">
                <a-form-item label="备注" name="short_name">
                  <a-input v-model:value="form.remark" placeholder="请输入备注" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-card>
      <a-card title="权限分配" class="smart-margin-bottom10">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :span="21">
            <a-form-item label="权限" name="auth">
              <auth-select v-model:checkedKeys="form.auth" v-model:selectedKeys="form.menu_id" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
    </a-form>
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import { ref, unref, computed, nextTick } from 'vue'
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
import { roleApi } from '@/api/system/role-api'
import authSelect from '@/components/system/role-form/index.vue'
import { title } from 'process'
const loadingStore = useLoadingStore()
// emit
const emit = defineEmits(['reload-list'])

// 组件ref
const formRef = ref()

const formDefault = {
  // 名称
  title: '',
  // 备注
  remark: '',
  // 权限
  auth: [],
  // 菜单id
  menu_id: undefined
}

const form = ref({ ...formDefault })
const rules = {
  title: [{ required: true, message: '请输入名称', trigger: 'blur' }]
}
// 是否展示抽屉
const visible = ref(false)

function showDrawer(rowData) {
  form.value = _.cloneDeep(formDefault)
  if (rowData.id && !_.isEmpty(rowData)) {
    form.value = _.pick(rowData, ['id', ...Object.keys(formDefault)])
    form.value.auth = rowData.menu_id.split(',').map(Number)
  }
  visible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

function onClose() {
  form.value = formDefault
  visible.value = false
}

function onSubmit() {
  formRef.value
    .validate()
    .then(async () => {
      // 提取表单数据
      const { title, remark, auth } = form.value
      const submitData = { title, remark, menu_id: auth.checked.join(',') }

      // 显示加载状态
      loadingStore.show()

      try {
        const action = unref(form).id ? roleApi.edit : roleApi.create
        await action(submitData)

        // 操作成功提示
        message.success('操作成功')
        // 关闭抽屉
        onClose()
        // 触发列表刷新
        emit('reload-list')
      } catch (error) {
        // 操作失败提示
        message.error(error.msg || '操作失败，请稍后重试')
        // 捕获错误
        errorSentry.captureError(error)
      } finally {
        // 隐藏加载状态
        loadingStore.hide()
      }
    })
    .catch((error) => {
      console.log('error', error)
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}

defineExpose({
  showDrawer
})

// 表单标题
const formTitle = computed(() => (form.value.id ? '编辑' : '新增'))
</script>
